<?php
class rank {
	public $result;
	
	function __set($id, $rank){
		if($this->isRanked($id)){
			$this->result = 'OK';
			return false;
		}
		$this->result = ($this->vote($id, $rank)) ? 'OK' : 'ERR';	
	}
	
	private function isRanked($id){
		global $db, $user;
		
		if(!$user->isLoggedIn())
			return true;

		$sql = "SELECT * FROM `" . RANKING_TABLE . "` WHERE `user_id` = '{$user->data['id']}' and `episode_id` = '{$id}' LIMIT 1";
		$db->query($sql);
		return (bool)$db->affected_rows();
		
	}
	
	private function vote($id, $rank){
		global $db, $user;
		
		$sql = "INSERT INTO `" . RANKING_TABLE . "` (`user_id`, `episode_id`, `rating`) VALUES ('{$user->data['id']}', '{$id}', '{$rank}')";
		return $db->query($sql);		
	}
	
	public function getRank($id){
		global $db, $user;
		
		if(!$user->isLoggedIn())
			return false;

		$sql = "SELECT `rating` FROM `" . RANKING_TABLE . "` WHERE `user_id` = '{$user->data['id']}' and `episode_id` = '{$id}' LIMIT 1";
		$db->query($sql);
		list($result) = $db->fetch_field('rating');
		
		if($db->affected_rows() == 0)
			$result = -1;
		return $result;
	}
	
	public function getMostlyRankedEpisodes(){
		global $db;
		
		$sql = "SELECT ROUND(AVG(r.`rating`),1) as `rank`, s.`seriesname`, s.`id`, e.`seasonnumber`, e.`episodenumber` FROM `" . RANKING_TABLE . "` r LEFT JOIN `" . EPISODES_TABLE . "` e on r.`episode_id` = e.`id` LEFT JOIN `" . SERIES_TABLE . "` s ON s.`id` = e.`seriesid` GROUP BY r.`episode_id` ORDER BY `rank` DESC LIMIT 5";
		$db->query($sql);
		$result = $db->fetch_assoc();
		
		return $result;
	}
	
	public function getAvRank($episode_id, $default = 5){
		global $db;
		$sql = "SELECT ROUND(AVG(`rating`),1) as `rank` FROM `" . RANKING_TABLE . "` WHERE `episode_id` = '{$episode_id}' GROUP BY `episode_id` LIMIT 1";
		$db->query($sql);
		list($result) = $db->fetch_field('rank');

		return ($result) ? $result : $default;
		
	}
}
?>